<template>
  <view>
    <nav-bar :page-title="lang.pageTitle"/>
    <view :class="['padding-30', locale]">
      <!-- header -->
      <view class="center margin-bottom-60">
        <text class="text-40">{{ lang.title }}</text>
      </view>

      <!-- ھۆججەت تاللاش -->
      <view v-if="!selectedFile" class="center gap-40 upload-box" @click="selectPDF">
        <image src="/static/upload/upload.svg" class="upload-icon"/>
        <view class="upload-text">{{ lang.selectFile }}</view>
      </view>

      <view v-else class="card flex-between selected-file">
        <view class="flex-center gap-20" style="width: 70%;">
          <view class="padding-30 radio-20 center pdf">
            <image src="/static/ext/pdf.svg" class="file-icon"/>
          </view>
          <view class="text-to text-32">{{ selectedFile.name }}</view>
        </view>
        <view class="column-center gap-20">
          <button class="btn preview" @click="previewFile">{{ toolBoxLang.preview }}</button>
          <button class="btn delete" @click="removeFile">{{ toolBoxLang.delete }}</button>
        </view>
      </view>

      <!-- نەتىجە -->
      <view v-if="result" class="result-card">
        <view class="center result-header">
          <text class="text-32 color-white">{{ lang.convertComplete }}</text>
        </view>

        <view class="result-content">
          <view class="flex-between result-item">
            <view class="text-32 color-dark-grey">{{ toolBoxLang.pageCount }}</view>
            <view class="text-color default-text">{{ result.page_count }} {{ otherLang.page }}</view>
          </view>

          <view class="flex-between gap-20 margin-bottom-30">
            <view class="color-white radio-30 center batch-btn" @click="handleBatchShare">
              {{ lang.batchShare }}
            </view>
            <view class="color-white radio-30 center batch-btn" @click="handleBatchDownload">
              {{ lang.batchDownload }}
            </view>
          </view>

          <view class="images-grid">
            <view v-for="(image, index) in result.images" :key="index" class="image-item">
              <image :src="image" mode="aspectFit" @click="previewImage(image)"/>
              <view class="image-actions">
                <view class="action-btn share" @click="shareImage(image)">{{ toolBoxLang.share }}</view>
                <view class="action-btn download" @click="downloadImage(image)">{{ toolBoxLang.download }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- مۇقىملاشتۇرۇش كۇنۇپكىسى -->
      <view class="padding-30 footer">
        <button class="submit-btn" :disabled="!selectedFile" @click="handleAction">
          {{ isConverted ? toolBoxLang.selectNewFile : lang.startConvert }}
        </button>
      </view>
    </view>
  </view>
</template>

<script lang="ts">
import NavBar from "@/components/nav-bar/nav-bar.vue";
import tips from "@/utils/tips";
import {pdf2imageUrl} from "@/services/office";

export default {
  components: {NavBar},
  data() {
    return {
      selectedFile: null,
      result: null,
      isConverted: false
    }
  },

  computed: {
    toolBoxLang() {
      return this.$t('toolBox')
    },
    lang() {
      return this.$t('toolBox.pdf2image')
    }
  },

  methods: {
    selectPDF() {
      uni.chooseMessageFile({
        count: 1,
        type: 'file',
        extension: ['.pdf'],
        success: (res) => {
          const {path, name} = res.tempFiles[0]
          this.selectedFile = {path, name}
        }
      })
    },

    removeFile() {
      this.selectedFile = null
      this.result = null
    },

    previewFile() {
      uni.openDocument({
        filePath: this.selectedFile.path,
        fileType: 'pdf',
        success: () => {
          console.log('ھۆججەت ئېچىلدى')
        }
      })
    },

    handleSubmit() {
      uni.showLoading()
      uni.uploadFile({
        url: pdf2imageUrl,
        filePath: this.selectedFile.path,
        name: 'file',
        success: (res) => {
          const {data} = JSON.parse(res.data)
          this.result = data
          this.isConverted = true
          tips.toast(this.lang.convertSuccess)
        },
        fail: () => {
          tips.toast(this.lang.convertFailed)
        },
        complete: () => {
          uni.hideLoading()
        }
      })
    },

    handleAction() {
      if (this.isConverted) {
        this.removeFile()
        this.isConverted = false
      } else {
        this.handleSubmit()
      }
    },

    previewImage(url: string) {
      uni.previewImage({
        urls: this.result.images,
        current: url
      })
    },

    // توپ ھالدا يوللاش
    async handleBatchShare() {
      uni.showLoading({title: this.lang.processing})
      try {
        const downloadTasks = this.result.images.map(url =>
            uni.downloadFile({url})
        )
        const results = await Promise.all(downloadTasks)

        for (const res of results) {
          if (res.statusCode === 200) {
            await uni.shareFileMessage({filePath: res.tempFilePath})
          }
        }
      } catch (error) {
        tips.toast(this.lang.shareFailed)
      }
      uni.hideLoading()
    },

    // توپ ھالدا ساقلاش
    async handleBatchDownload() {
      uni.showLoading({title: this.lang.processing})
      try {
        const downloadTasks = this.result.images.map(url =>
            uni.downloadFile({url})
        )
        const results = await Promise.all(downloadTasks)

        for (const res of results) {
          if (res.statusCode === 200) {
            await uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath
            })
          }
        }
        tips.toast(this.lang.saveSuccess)
      } catch (error) {
        tips.toast(this.lang.saveFailed)
      }
      uni.hideLoading()
    },

    downloadImage(url: string) {
      uni.downloadFile({
        url,
        success: (res) => {
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              tips.toast(this.toolBoxLang.saveSuccess)
            }
          })
        }
      })
    },

    shareImage(url: string) {
      uni.downloadFile({
        url,
        success: (res) => {
          uni.shareFileMessage({
            filePath: res.tempFilePath,
            success: () => {
              console.log('رەسىم يوللاندى')
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-box {
  border: 2px dashed $uni-border-color;
  padding: 60rpx;

  .upload-icon {
    width: 80rpx;
    height: 80rpx;
  }

  .upload-text {
    font-size: 32rpx;
    color: #666;
  }
}

.selected-file {
  .file-icon {
    width: 60rpx;
    height: 60rpx;
  }

  .btn {
    font-size: 24rpx;
    color: #fff;
    width: 128rpx;
    border-radius: 12rpx;
    padding: 0;
    margin: 0;

    &.preview {
      background: #007AFF;
    }

    &.delete {
      background: #ff3b30;
    }
  }
}

.result-card {
  margin-top: 30rpx;
  border-radius: 20rpx;
  background: #ffffff;
  overflow: hidden;
  margin-bottom: 180rpx;

  .result-header {
    background: $uni-color-success;
    padding: 20rpx;
  }

  .result-content {
    padding: 30rpx;

    .result-item {
      margin-bottom: 20rpx;
    }

    .batch-btn {
      flex: 1;
      height: 80rpx;
      background: $uni-color-primary;
      font-size: 28rpx;

      &:first-child {
        background: $uni-color-warning;
      }
    }

    .images-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 20rpx;
      margin-top: 30rpx;

      .image-item {
        position: relative;
        border-radius: 16rpx;
        overflow: hidden;

        image {
          width: 100%;
          height: 300rpx;
        }

        .image-actions {
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          display: flex;
          justify-content: space-around;
          padding: 10rpx;
          background: rgba(0, 0, 0, 0.6);

          .action-btn {
            color: #fff;
            font-size: 24rpx;
            padding: 6rpx 20rpx;
            border-radius: 30rpx;

            &.share {
              background: $uni-color-warning;
            }

            &.download {
              background: $uni-color-success;
            }
          }
        }
      }
    }
  }
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);

  .submit-btn {
    width: 100%;
    height: 90rpx;
    background: linear-gradient(to right, #34c759, #30d158);
    color: #fff;
    font-size: 32rpx;
    border-radius: 46rpx;

    &[disabled] {
      background: linear-gradient(to right, #ccc, #ddd);
    }
  }
}
</style>
